from rest_framework import serializers
from rest_framework.exceptions import APIException
from patient.models import HospitalInfo
from .models import RegisterInfo, DetailedList
from user.models import Medicine
import re

import re

from rest_framework import serializers

from .models import RegisterInfo, DetailedList

from utils.common_response import APIResponse

from patient.models import HospitalInfo


# class RegisterInfoSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = RegisterInfo
#
#         # fields = ['id',
#         #           'name',
#         #           'gender',
#         #           'gender_name',
#         #           'data_birth',
#         #           'mobile',
#         #           'subscribe_time',
#         #           'illness_desc',
#         #           'department',
#         #           'department_name',
#         #           'department_type_name',
#         #           'doctor',
#         #           'doctor_name']
#         # extra_kwargs = {
#         #     'gender_name': {'read_only': True},
#         #     'department_name': {'read_only': True},
#         #     'department_type_name': {'read_only': True},
#         #     'doctor_name': {'read_only': True},
#         # }
#
#         fields = [
#             'id',
#             'name',
#             'gender',
#             'gender_name',  # 只读
#             'data_birth',
#             'mobile',
#             'subscribe_time',
#             'illness_desc',
#             'department',
#             'doctor',
#             'department_name',  # 只读
#             'department_type_name',  # 只读
#             'doctor_name',  # 只读
#         ]
#
#         extra_kwargs = {
#             'gender_name': {'read_only': True},
#             'department_name': {'read_only': True},
#             'department_type_name': {'read_only': True},
#             'doctor_name': {'read_only': True},
#         }
#
#     def _get_mobile(self, attrs):
#         mobile = attrs.get('mobile')
#         if re.match(r'^1[3-9][0-9]{9}$', str(mobile)):
#             return attrs
#         else:
#
#             raise APIException('手机号不规范')
#
#     # def validate(self, attrs):
#     #     self._get_mobile(attrs)
#     #         return APIResponse({'code': 255, 'msg': '手机号格式不规范'})
#
#     # 入库前的准备
#     def validate(self, attrs):
#         # 检查手机号
#         self._get_mobile(attrs)
#         return attrs
#
#     def create(self, validated_data):
#         res = super().create(validated_data)
#         self.context['doctor_name'] = res.doctor.name
#         return res

class RegisterInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = RegisterInfo
        fields = [
            'id',
            'name',
            'gender',
            'gender_name',  # 只读
            'data_birth',
            'mobile',
            'subscribe_time',
            'illness_desc',
            'department',
            'doctor',
            'department_name',  # 只读
            'department_type_name',  # 只读
            'doctor_name',  # 只读
        ]
        extra_kwargs = {
            'gender_name': {'read_only': True},
            'department_name': {'read_only': True},
            'department_type_name': {'read_only': True},
            'doctor_name': {'read_only': True},
        }

    def _get_mobile(self, attrs):
        mobile = attrs.get('mobile')
        if re.match(r'^1[3-9][0-9]{9}$', str(mobile)):
            return attrs
        else:
            raise APIException('手机号不规范')

    def validate(self, attrs):

        self._get_mobile(attrs)

    # 入库前的准备
    def validate(self, attrs):

        # 检查手机号
        self._get_mobile(attrs)

        return attrs

    def create(self, validated_data):

        res = super().create(validated_data)
        self.context['doctor_name'] = res.doctor.name
        return res


#
# class DetailedListSerializer(serializers.ModelSerializer):

class ListDetailSerializer(serializers.ModelSerializer):
    medicine = serializers.ListField(write_only=True)

    class Meta:
        model = DetailedList
        fields = ['id', 'patient_name', 'doctor_name', 'mobile', 'total_price', 'careful_note', 'medicine',
                  'medicine_list', 'status_name', 'price']

    price = serializers.SerializerMethodField(read_only=True)

    def get_price(self, obj):
        try:
            user = HospitalInfo.objects.get(name=obj.patient_name)
            return str(int(obj.total_price) + (int(user.time_length) * 50))
        except Exception as e:
            return obj.total_price

    status_name = serializers.SerializerMethodField(read_only=True)

    def get_status_name(self, obj):
        return obj.get_status_display()

    medicine_list = serializers.SerializerMethodField(read_only=True)

    def get_medicine_list(self, obj):  # 列表里面套字典
        medicine_info_list = []
        for medicine in obj.medicine.all():
            medicine_info_list.append(
                {'id': medicine.id, 'medicine_name': medicine.name, 'medicine_price': medicine.price,
                 'medicine_category': medicine.category})
        return medicine_info_list


############# 药品开单 序列化

class DetailedListSerializer(serializers.ModelSerializer):
    medicine = serializers.ListField(write_only=True)

    class Meta:
        model = DetailedList
        fields = ['id', 'patient_name', 'doctor_name', 'mobile', 'total_price', 'careful_note', 'medicine',
                  'medicine_list', 'status_name', 'price']

    price = serializers.SerializerMethodField(read_only=True)

    def get_price(self, obj):
        try:
            user = HospitalInfo.objects.get(name=obj.patient_name)
            return str(int(obj.total_price) + (int(user.time_length) * 50))
        except Exception as e:
            return obj.total_price

    status_name = serializers.SerializerMethodField(read_only=True)

    def get_status_name(self, obj):
        # 显示缴费状态的中文
        return obj.get_status_display()

    medicine_list = serializers.SerializerMethodField(read_only=True)

    def get_medicine_list(self, obj):  # 列表里面套字典
        medicine_info_list = []
        for medicine in obj.medicine.all():
            medicine_info_list.append(
                {'id': medicine.id, 'medicine_name': medicine.name, 'medicine_price': medicine.price,
                 'medicine_category': medicine.category})
        return medicine_info_list